<!DOCTYPE html>



<html>

    <head>
        <title>Vogoni</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
<?php
require_once 'inc/mysql.inc.php';
require_once 'inc/functions.php';

function GrantyLisp($event_id) {
    $gs = SQLGrantyEvent($event_id);
    $out = "";
    foreach ($gs as $g) { //print_r($row);
        $out = $out . ' "' . $g['Name'].'"';
    }
    return($out);
}

function MichalTime($t){
    return ( sprintf("%s/60", strval(60*date("H", $t) +  date("M", $t))  ));
}

function OpenFileBOM($fn){
  $fh = fopen($fn, 'w');
  if ($fh==FALSE) printf("ERROR: File %s opening failed<br>", $fn);
  fwrite($fh, "\xEF\xBB\xBF"); // BOM
  return $fh;  
}

// Get SQL data

//print_r( $_GET);



session_start();  
$_SESSION['lid'] = 0 ;   // the user with id 0 must exist in the database
require_once 'inc/vogoni.startsession.php';

$mesic=$_GET['m'];
$rok=$_GET['y'];
$kdo=$_GET['p'];


if (!(isset($rok))){
    $rok = date("Y");
}


if (isset($mesic)){
    $time_filter = sprintf("(MONTH(e.DateBegin)=%d OR MONTH(e.DateEnd)=%d) AND (YEAR(e.DateBegin)=%d OR YEAR(e.DateEnd)=%d)",
        $mesic, $mesic, $rok, $rok);
} else {
    $time_filter = sprintf("(YEAR(e.DateBegin)=%d OR YEAR(e.DateEnd)=%d)",
        $rok, $rok);
}

if (isset($kdo)){
    $personal_filter = sprintf(" WHERE (e.person = '%s' "
            ." OR e.id IN (SELECT  event FROM `GuestsInSimpleEvents` g WHERE g.person = '%s')) AND ",
            $kdo, $kdo);
} else $personal_filter = " WHERE  ";


$sql = "SELECT * FROM `SimpleEvents` e ". $personal_filter .  $time_filter;
echo $sql."<br>";
$udalosti = mysql_query($sql) or die(mysql_error());
echo "Celkem ".mysql_num_rows($udalosti)." udalostí k exportu.<br><br>";

// Open files
$outDir = "exports/";
echo "Expoting to ".realpath($outDir)."<br>";
if (!is_writable($outDir)) die ("Error: directory $outDir is not writable.");
$fs = array(
    1 => OpenFileBOM($outDir."Dovolena.lisp"),
    2 => OpenFileBOM($outDir."Sluzebky.lisp"),
    3 => OpenFileBOM($outDir."Aktivity.lisp"),
    4 => OpenFileBOM($outDir."Zakazano.lisp")
    );


// export data
try {
    while ($row = mysql_fetch_assoc($udalosti)) {
        echo $row['id']."<br>";
        print_r($row);
        echo "<br>";
        
        $jmeno=$_SESSION['Global']['People'][$row['person']][':schedule-alias'];
        $od=strtotime($row['DateBegin']);
        $do=strtotime($row['DateEnd']);

        $out = "";
        switch ($row['type'])  {
            case 1:
                $out = sprintf('(:DOVOLENA "%s" (%s) (%s))',
                        $jmeno, date("Y m d", $od), date("Y m d", $do));
                break;

            case 2:
                $out = sprintf('(:SLUZEBKA "%s" (%s) (%s) %s)',
                        $jmeno, date("Y m d", $od), date("Y m d", $do), GrantyLisp($row['id']));
                break;

            case 3:
                // people
                $sql = "SELECT person p FROM GuestsInSimpleEvents g WHERE g.`event` = ".$row['id'];
                $result = mysql_query($sql) or die(mysql_error());
                $resultset=array();
                while ($person = mysql_fetch_array($result)) {
                    $resultset[] = '"'.$_SESSION['Global']['People'][$person['p']][':schedule-alias'].'"';
                }
                $guests_list = implode(" ", $resultset);

                // the output
                $out = sprintf('(:AKTIVITA "%s" (%s) %s '
                              .'(%s) %s %s )',
                    $row['Reason'], $guests_list, GrantyLisp($row['id']), 
                    date("Y m d", $od),   MichalTime($od), MichalTime($do) );
                break;

            case 4:
                // people
                $sql = "SELECT person p FROM GuestsInSimpleEvents g WHERE g.`event` = ".$row['id'];
                $result = mysql_query($sql) or die(mysql_error());
                $resultset=array();
                while ($person = mysql_fetch_array($result)) {
                    $resultset[] = '"'.$_SESSION['Global']['People'][$person['p']][':schedule-alias'].'"';
                }
                $guests_list = implode(" ", $resultset);

                // the output
                $out = sprintf('(:ZAKAZANO "%s" %s (%s) '
                              .'(%s) %s %s )',
                    $row['Reason'], GrantyLisp($row['id']), $guests_list,
                    date("Y m d", $od),   MichalTime($od), MichalTime($do) );
                break;
        }
        echo "<tt>".$out."</tt><br>";
        fwrite($fs[$row['type']], $out.' ; '.$row['id']."\n");
    }
    echo "konec";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

fclose($fs[1]);
fclose($fs[2]);
fclose($fs[3]);
fclose($fs[4]);


?>
</body>
</html>
